package com.imau.controller;

import com.imau.bean.User;
import com.imau.service.UserService;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@WebServlet("/login")
public class UserLoginServlet extends HttpServlet {

    //定义服务层对象
    private UserService userService = new UserService();

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

        //设置编码
        req.setCharacterEncoding("utf-8");
        resp.setContentType("text/html;charset=utf-8");
        //获取表单数据
        String username = req.getParameter("username");
        String password = req.getParameter("password");
        String remember = req.getParameter("remember");


        //校验登录
        User user = userService.checkLogin(username, password);

        //判断并响应客户端
        if(user != null)
        {

            //登录成功，将用户信息存储到session中
            req.getSession().setAttribute("user",username);

            //1.是否选中记住我
            if("1".equals(remember))
            {
                //创建cookie
                Cookie userNameCookie = new Cookie("username",username);
                Cookie passwordCooke = new Cookie("password",password);
                //设置存活时间
                userNameCookie.setMaxAge(60*60*24*7);
                passwordCooke.setMaxAge(60*60*24*7);
                //发送cookie
                resp.addCookie(userNameCookie);
                resp.addCookie(passwordCooke);
            }else {//未选中时，销毁所有cookie

                //获取所有cookie
                Cookie[] cookies = req.getCookies();
                //销毁username password的cookie
                for(Cookie cookie :cookies)
                {
                    if("username".equals(cookie.getName()) ||  "password".equals(cookie.getName()))
                    {
                        cookie.setMaxAge(0);
                    }
                }



            }


             resp.sendRedirect(req.getContextPath()+"/brand.html");
        }else {
            resp.sendRedirect(req.getContextPath()+"/login.html");
        }
    }

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        this.doPost(req,resp);
    }
}
